package hn.cch.https;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * HTTP事件处理
 */

@Component
public class HttpsHandler extends ChannelInboundHandlerAdapter {


    private static Logger logger = LoggerFactory.getLogger(HttpsHandler.class);


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelReadComplete");
        ctx.flush();
        logger.info("ctx.flush");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("exceptionCaught");
        cause.printStackTrace();
        ctx.close();
        logger.info("ctx.close");

    }




    private boolean keepAlive = false;
    private int contentLength = 0;

    private ByteBuf byteBuf = null;
    private String uri = null;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        logger.info("http message class : " + msg.getClass());

        if (msg instanceof HttpRequest) {
            logger.info("http message class : HttpRequest");
            HttpRequest httpRequest = (HttpRequest) msg;


            keepAlive = HttpUtil.isKeepAlive(httpRequest);
            logger.info("http keep alive : " + keepAlive);

            contentLength = (int) HttpUtil.getContentLength(httpRequest);
            logger.info("http content length : " + contentLength);
            byteBuf = ctx.alloc().heapBuffer(contentLength);


            uri = httpRequest.uri();
            logger.info("http uri : " + uri);

        }

        if (msg instanceof HttpContent) {
            logger.info("http message class : HttpContent");
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf contentByteBuf = httpContent.content();
            contentByteBuf.readBytes(byteBuf);
            // contentByteBuf.release();


            if (msg instanceof LastHttpContent) {
                logger.info("http message class : LastHttpContent");
                byte[] bytes = new byte[contentLength];
                byteBuf.readBytes(bytes);
                byteBuf.release();

                logger.info("bytes:", new String(bytes));

                byte[] content = "{\"time\":\"2020-11-18 10:10:10\"}".getBytes();

                DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK, Unpooled.wrappedBuffer(content));

                defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN)
                        .setInt(HttpHeaderNames.CONTENT_LENGTH, defaultFullHttpResponse.content().readableBytes());

                if (keepAlive) {
                    defaultFullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                    ctx.write(defaultFullHttpResponse);
                }else {
                    ctx.write(defaultFullHttpResponse).addListener(ChannelFutureListener.CLOSE);
                }


            }
        }
    }


}

